/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.stock.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.zhengjie.jdbcLinkDb.JdbcToDbService;
import me.zhengjie.modules.stock.domain.Stock;
import me.zhengjie.modules.stock.domain.StockStore;
import me.zhengjie.modules.stock.repository.StockStoreRepository;
import me.zhengjie.modules.stock.service.StockStoreService;
import me.zhengjie.modules.stock.service.dto.*;
import me.zhengjie.modules.stock.service.mapstruct.StockStoreMapper;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.stock.repository.StockRepository;
import me.zhengjie.modules.stock.service.StockService;
import me.zhengjie.modules.stock.service.mapstruct.StockMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2021-10-14
**/
@Service
@RequiredArgsConstructor
public class StockStoreServiceImpl implements StockStoreService {

    private final StockStoreRepository stockStoreRepository;
    private final StockStoreMapper stockStoreMapper;

    private String url="http://api.mairui.club/hslt/list/893591c193102e821c";


    @Resource
    private JdbcToDbService jdbcToDbService;

    @Override
    public Map<String,Object> queryAll(StockStoreQueryCriteria criteria, Pageable pageable){
        Page<StockStore> page = stockStoreRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        jdbcToDbService.delStock();
        List<StockStore> stocks = jdbcToDbService.getStockStore();
//        for (StockStore stock:stocks){
//            System.out.println(stock.getStockName());
//        }
        return PageUtil.toPage(page.map(stockStoreMapper::toDto));
    }

    @Override
    public List<StockStoreDto> queryAll(StockStoreQueryCriteria criteria){
        return stockStoreMapper.toDto(stockStoreRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public StockStoreDto findById(Long id) {
        StockStore stock = stockStoreRepository.findById(id).orElseGet(StockStore::new);
        ValidationUtil.isNull(stock.getId(),"StockStore","id",id);
        return stockStoreMapper.toDto(stock);
    }

    @Override
    public StockStoreDto create(StockStore resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(IdUtil.simpleUUID());
        jdbcToDbService.insertStock();
        return stockStoreMapper.toDto(stockStoreRepository.save(resources));
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(StockStore resources) {

//        stockStoreRepository.save(stock);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            stockStoreRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<StockStoreDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StockStoreDto stock : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("股票名称", stock.getStockName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }



    public void initData(){

        String result = sendGet();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<StockStore> list = new ArrayList<>();
            List<StockData> myEntityList = objectMapper.readValue(result, new TypeReference<List<StockData>>() {});
            for (StockData stockData : myEntityList) {
                StockStore stockStore = new StockStore();
                stockStore.setId(IdUtil.simpleUUID());
                stockStore.setStockCode(stockData.getDm());
                stockStore.setStockName(stockData.getMc());
                stockStore.setJys(stockData.getJys());
                stockStore.setCreateTime(new Timestamp(new Date().getTime()));
                list.add(stockStore);
            }
            stockStoreRepository.saveAll(list);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
//        System.out.println(result);


    }

    public String sendGet() {
        String result = "";
        BufferedReader in = null;// 读取响应输入流
        try {
            // 创建URL对象
            java.net.URL connURL = new java.net.URL(url);
            // 打开URL连接
            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
                    .openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpConn.setRequestProperty("Content-Type", "application/json");
//            httpConn.setRequestProperty("Authorization", authorization);
            // 建立实际的连接
            httpConn.connect();
            // 定义BufferedReader输入流来读取URL的响应,并设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn
                    .getInputStream(), "UTF-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}